<?php
use App\Models\User;

/**
 * 检查远程文件是否存在
 */
if (!function_exists('remote_file_exists')) {
	function remote_file_exists($url) {
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		$result = curl_exec($curl);
		$is_exists = false;
		if ($result !== false) {
			$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			if ($statusCode == 200) {
				$is_exists = true;
			} elseif ($statusCode == 304) {
				$is_exists = true;
			}
		}
		curl_close($curl);
		return $is_exists;
	}
}

/**
 * 获取用户目录
 */
if (!function_exists('get_user_dir')) {
	function get_user_dir($uid) {
		return 'upload/u' . base_convert(ceil($uid / 2000), 10, 36) . '/' . base_convert($uid, 10, 36) . '/';
	}
}

/**
 * 获取用户照片
 */
if (!function_exists('get_photo')) {
	function get_photo($uid) {
		$src = asset('assets/avatar/' . strval($uid % 40) . '.jpg');
		$user = User::find($uid);
		if (empty($user)) {
			return $src;
		}
		if (empty($user->photo)) {
			return $src;
		}
		if (filter_var($user->photo, FILTER_VALIDATE_URL) !== FALSE) {
			return $user->photo;
		}
		if (file_exists($user->photo)) {
			return asset($user->photo);
		}
		return $src;
	}
}

/**
 * 获取用户头像
 */
if (!function_exists('get_avatar')) {
	function get_avatar($uid) {
		$face = 'upload/avatar/' . $uid . '.jpg';
		if (file_exists(public_path() . DS . $face)) {
			return asset($face);
		}
		return asset('assets/avatar/' . strval($uid % 40) . '.jpg');
	}
}